package tools.ga;

import java.util.Random;


public class GeneralProportionSelection {

    private float[][] proUpLowNo;
    private int[] individualNo;
    private Individual[] populationAfterSelection;

    public GeneralProportionSelection(Individual[] population) throws CloneNotSupportedException {
       populationAfterSelection=new Individual[population.length];
        this.proUpLowNo = new float[population.length][2];
        this.individualNo = new int[population.length];
         float temValue = 0, sumValue =0;
        for (Individual population1 : population) {
            sumValue += population1.getFitness();
        }
        for (int i = 0; i < population.length; i++) { //calculate the probabiltiysum

            proUpLowNo[i][0] = temValue;
            proUpLowNo[i][1] = temValue +(population[i].getFitness() / sumValue);
            temValue = proUpLowNo[i][1];
        }
        float temd;
        Random r = new Random();
        for (int i = 0; i < population.length; i++) {
            temd = r.nextFloat();
            for (int j = 0; j < population.length; j++) {
                if (temd <= proUpLowNo[j][1] && temd >= proUpLowNo[j][0]) {
                    individualNo[i] = j;
                    break;
                }
            }
        }
        for (int i = 0; i < population.length; i++) {
            populationAfterSelection[i]=population[i].clone();
        }
    }

    /**
     * @return the populationAfterSelection
     */
    public Individual[] getPopulationAfterSelection() {
        return populationAfterSelection;
    }
}